import requests
import json
import re
from bs4 import BeautifulSoup
import time

def get_price_and_shipping(url):
    # 设置headers模拟浏览器访问
    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh,en-US;q=0.9,en;q=0.8,ja;q=0.7,zh-CN;q=0.6,zh-TW;q=0.5',
        'cache-control': 'max-age=0',
        'cookie': 'arms_uid=f9d03560-6f0d-426e-b023-3d883115638b; leftMenuLastMode=EXPEND; leftMenuModeTip=shown; cookie2=11683b206198c37d1f47ae3dbf0039f4; t=ec74a1aa00859705af234439ca7ce055; _tb_token_=541e36fbd1346; cna=mN5ZIH5PqiUCAd3bAjn8pC0O; xlly_s=1; _bl_uid=Rpmgt8a572kg5kuIh726u14gII9z; taklid=c434b85a926a413fa467b580dd88e5a7; JSESSIONID=A334F4F7CD32476ADDB7CCFA389E6D8B; cookie1=U7H1q24fyXoOU2WfazdP0qDTd%2BPDvRZLguo2JM5j2Oc%3D; cookie17=VWwxsFURJ97z; sgcookie=E100MT9msR0FDVj9%2BePxG9EQ6O290X3D57pGIJkC0XQSDnD8ID7fX28Kz6hMLO7mztMDAToPuP0FNOqSZTPwSeDmAkQGtkvYjc3cI7I38k2GykbkPMroJOwSEq1FHakHO4HB; sg=153; csg=c0d34563; lid=lwlfly001; unb=631217245; uc4=id4=0%40V8354BMKdwb%2FOHek2biPnKlnwu0%3D&nk4=0%40Dff1rPnYm9vpaN2oUi2otatT9%2B8%3D; _nk_=lwlfly001; last_mid=b2b-631217245; _csrf_token=1741877514169; __cn_logon__=true; __cn_logon_id__=lwlfly001; __last_loginid__=b2b-631217245; __last_memberid__=b2b-631217245; mtop_partitioned_detect=1; _m_h5_tk=c82e0733e29a657c5efdf8bafdc71544_1741960402386; _m_h5_tk_enc=1181dd67a788294b608477785a2bda16; _m_h5_c=b205cb68ca637060b0f09ae986499cce_1741958242670%3Bfe52132f8fc75ec9a12539ab582f3fec; x5sec=7b22733b32223a2261396139633833653835366331643730222c226c61707574613b32223a226464316639613135323865663730623736303861303230323037306632396639434a6177304c344745504766367644362f2f2f2f2f774561437a597a4d5449784e7a49304e5473784d50617371536f3d227d; isg=BB0dKFnpJmjTNMJCvwvgUiS0LP8XOlGMgi-ORd_ju3SjljnIp4gZXRYVw4KQFmlE; _user_vitals_session_data_={"user_line_track":true,"ul_session_id":"mdc9ed54py","last_page_id":"detail.1688.com%2Fpljmfcf0j0i"}; tfstk=gvf-KG4n1r3RU2OgZ7wmtebA4LU0s6QPDg7stHxodiIAbGh3zTjhHIT9PD9Q4QfdDisGKTvHNm9XSFGINYTScxTMypsHxa4KzsIttbqzUwGptBZgj5VGzzReOl0J9Y3y4e7XArvWZs7K7BZgjSVGzaReOgcZ9g9xhF-XPb9WArnXJUOBRUOQknTp7vi5ABaYke-XABOCAZav8f1ZgHyBjXBse17H2wtxOX1vPu-1ynL2usLJehNwDXBPMUpJfa1kKDmBJO19UGZmE36OQGLGqSGRXasRCd1ScodFoOIpW_asBHIPl_vfNyDwuBW5CQ1LX0_R2g5PCaZmHEBfrspc1lhpUtsPQpC3m5RlINfeC_N-bnvwJGd5HoGRfg-Cs1pWZcx9-YaYkvkeFEo1b5qFD_nUKEKgogMELKHwkh4YUvkeFE8vjrAmLvJxQ',
        'priority': 'u=0, i',
        'referer': 'https://detail.1688.com/offer/725443957659.html?spm=a261y.7663282.3002526303362591.2.736a6a1e656Npn&sk=order',
        'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate', 
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
    }
    
    try:
        # 发送请求获取页面内容
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'utf-8'
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # 将结果保存到文件以便调试
            with open('page_content.html', 'w', encoding='utf-8') as f:
                f.write(response.text)
            
            price_range_match = re.search(r'"skuRangePrices":(\[.*?\])', response.text)
            if price_range_match:
                print(price_range_match.group(1))
                price_ranges = json.loads(price_range_match.group(1))
                if price_ranges:
                    min_price = price_ranges[0]['price']
                    max_price = price_ranges[-1]['price']
                    price_range = f"价格区间：¥{min_price} - ¥{max_price}"
                else:
                    price_range = "未找到价格信息"
                
                # # 提取运费信息
                # freight_info = product_data.get('freightInfo', {})
                # shipping_fee = freight_info.get('defaultFreightPrice', '未知')
                # shipping_info = f"运费：¥{shipping_fee}"
                
                return {
                    "价格信息": price_range,
                    # "运费信息": shipping_info
                }
            
        return "无法获取页面信息"
    
    except Exception as e:
        return str(e)  # 直接返回错误信息，不进行字符串格式化

# 使用示例
if __name__ == "__main__":
    product_id = '780932392150'
    url = f"https://detail.1688.com/offer/{product_id}.html?offerId={product_id}&spm=a260k.home2024.recommendpart.5"
    result = get_price_and_shipping(url)
    print(result)